
import api from '../../api/index'
import { userInfoStore } from '../../store/userInfo'

const app = getApp()

Page({

  data: {
    pageNo:1,
    pageSize:10,
    userInfo:{},
    type:1,
    sheet:0,
    areaData:[],
    customer:[],
    finish:false,
    qrType:0,
    maskHidden: false, 
    imagePath:'',
    canvasW:'641px',
    canvasH:'892px', 
    canvasW1: '750px',
    canvasH1: '1628px',
    canvasW2: '1081px',
    canvasH2: '1080px',
  },
  
  onLoad: function (options) {
    this.setData({ userInfo: userInfoStore.userInfo})
    this.getData();
  },

  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {

  },

  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {

  },

  showCoupon:function(e){
    wx.navigateTo({
      url: 'coupon',
    })
  },

  showReceiveOrder:function(e){
    wx.navigateTo({
      url: 'order',
    })
  },

  showRanking:function(e){
    let url ='https://www.daikin1995.com/ranking-phone.html';
    wx.navigateTo({
      url: '../webView/index?url=' + encodeURIComponent(url),
    })
  },

  tel:function(e){
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },

  getData:function(){
    let param = {
      id: this.data.userInfo.id,
      type: this.data.type,
      page: this.data.pageNo,
      pageSize: this.data.pageSize
    }
    var self=this
    api.getareadata(param).then(res => {
      self.setData({ areaData: res.result })
    }, err => { 
      
    })

    api.getmycustomer(param).then(res => {
      let { result } = res;
      self.data.customer.push(...result);
      let finish = false;
      if (result.length < self.data.pageSize) finish = true;
      self.setData({ customer: res.result, finish: finish })
      wx.stopPullDownRefresh();
    }, err => { 
      self.setData({ finish: true })
      wx.stopPullDownRefresh();
    })
  },

  selectItem:function (e) {
    let self=this
    this.setData({ type: e.currentTarget.dataset.index, 
      pageNo: 1, 
      areaData:[],
      customer: [], 
      finish: false},()=>{
      self.getData();
    });
  },

  selectSheet:function (e) {
    let self = this
    if(e.currentTarget.dataset.index==0){
      this.setData({
        sheet: e.currentTarget.dataset.index,
        pageNo: 1,
        areaData: [],
        customer: [],
        finish: false
      }, () => {
        self.getData();
      });
    } else{
      this.setData({
        sheet: e.currentTarget.dataset.index,
        areaData: []
      }, () => {

      });
    }
  },

  closeMask: function () {
    this.setData({
      maskHidden: !this.data.maskHidden
    });
  },

  savePosteToPhotosAlbum: function (e) {
    console.log(this.data.imagePath);
    wx.saveImageToPhotosAlbum({
      filePath: this.data.imagePath,
      success(res) {
        wx.showToast({
          title: '已保存到相册~',
        })
      }
    });
  },

  drawCanvas: function (tempQrFilePath, success, fail){
    var self = this;
    var context = wx.createCanvasContext('postecanvas');
    if (this.data.qrType==1)
    context.drawImage('../../images/default.png', 0, 0, 641, 892);
    else
    context.drawImage('../../images/qrbg.png', 0, 0, 750, 1628);
    context.save();

    //码
    if (this.data.qrType == 1){
      context.drawImage(tempQrFilePath, 120, 220, 400, 400);
      
      let code = '编码:' + this.data.userInfo.recomendCode;
      context.setFontSize(40);
      context.setFillStyle('#000000');
      context.setTextAlign('center');
      context.fillText(code, 320, 700);
      context.stroke();
    }
    else if (this.data.qrType == 3){
      context.drawImage(tempQrFilePath, 340, 510, 400, 400);

      let code = '编码:' + this.data.userInfo.recomendCode;
      context.setFontSize(35);
      context.setFillStyle('#000000');
      context.setTextAlign('center');
      context.fillText(code, 540, 980);
      context.setFontSize(30);
      context.fillText("扫码了解更多", 540, 1030);
      context.stroke();

    }
    else
    {
      
      // var r = 200;
      // var x = 119;
      // var y = 265;
      // var d = 2 * r;
      // var cx = x + r;
      // var cy = y + r;
      // context.arc(cx, cy, r, 0, 2 * Math.PI);
      // context.clip();
      // context.drawImage(tempQrFilePath, x, y, d, d);
      // context.restore()
      // context.setFillStyle('#ffffff');
      // context.fillRect(139, 285, 360, 360);
      context.drawImage(tempQrFilePath, 70, 1436, 120, 120);
      // context.restore();
      let code = '编码:' + this.data.userInfo.recomendCode;
      context.setFontSize(18);
      context.setFillStyle('#ffffff');
      context.setTextAlign('center');
      context.fillText(code, 130, 1580);
      context.stroke();
    }

    context.draw(false, function () {
      wx.canvasToTempFilePath({
        canvasId: 'postecanvas',
        success: function (res) {
          success(res.tempFilePath);
        },
        fail:function(){
          fail('图片保存失败')
        }
      })
    });
  },

  createQR:function (e) {
    if (!this.data.userInfo.recomendCode){
      wx.showModal({
        titile:"提示",
        content: "您还没有编码",
        showCancel: false,
        confirmText: "我知道了"
      })
      return;
    }
    
    let qt = e.currentTarget.dataset.type;
    this.setData({ qrType: qt}, ()=>{
      console.log('aaaabbbbbb')
    })

    var failCallback = function (errMsg) {
      wx.hideToast();
      wx.showModal({
        title: errMsg,
        content: '知道了',
        showCancel: false
      })
    };
    wx.showToast({
      title: '绘制中...',
      icon: 'loading'
    })
    var self = this
    if (!this.data.userInfo.qrimageurl){
      let param = {
        page:'pages/index',
        scene: this.data.userInfo.recomendCode,
        width:800,
        auto_color:true
      }    
      api.getQr(param).then(res => {
        let { result } = res;
        let { userInfo } = userInfoStore;
        userInfo.qrimageurl = result;
        userInfoStore.updateUserInfo(userInfo);
        wx.downloadFile({
          url: result,
          success: function (res) {
            if (res.statusCode === 200) {
              self.drawCanvas(res.tempFilePath, function (filePath) {
                wx.hideToast();
                self.setData({
                  imagePath: filePath,
                  maskHidden: true
                });
              }, failCallback);
            } else {
              failCallback('下载二维码失败[' + res.statusCode + ']')
            }       
          }, fail: function (res) {
            failCallback('下载二维码失败')
          }
        }) 
        api.saveUser({ OpenId: userInfo.openId, qrimageurl:result}).then(res=>{
        },err=>{
        })
      },err=>{
        failCallback(err) 
      })
    } else {
      wx.downloadFile({
        url: this.data.userInfo.qrimageurl,
        success: function (res) {
          if (res.statusCode === 200) {
            self.drawCanvas(res.tempFilePath, function(filePath){
              wx.hideToast();
              self.setData({
                imagePath: filePath,
                maskHidden: true
              });
            }, failCallback);
          } else {
            failCallback('下载二维码失败[' + res.statusCode + ']')
          }
        }, fail: function (res) {
          console.log(res)
          failCallback('下载二维码失败')
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let self = this;
    this.setData({ sheet:0, pageNo: 1, customer: [], finish:false},()=>{
      self.getData();
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.finish) return;
    console.log('bbb=', this.data.pageNo)
    this.data.pageNo++;
    console.log('aaa=', this.data.pageNo)
    let self = this;
    this.setData({ pageNo: this.data.pageNo},()=>{
      let param = {
        id: self.data.userInfo.id,
        type: self.data.type,
        page: self.data.pageNo,
        pageSize: self.data.pageSize
      }
      api.getmycustomer(param).then(res => {
        let {result} = res;
        self.data.customer.push(...result);
        let finish = false;
        if (result.length < self.data.pageSize) finish=true;
        
        self.setData({ customer: self.data.customer, finish: finish});
      }, err => { })

    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    getApp().share();
  }
})